package com.jqsoft.launcher.login;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.MainFunctionActivity;
import com.jqsoft.launcher.activity.SettingIPActivity;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.AndroidUtil;
import com.jqsoft.launcher.util.ByteOrderUtil;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.NetUtil;
import com.jqsoft.launcher.util.StringTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.otg.idcard.OTGReadCardAPI;

/**
 * 登录
 * 
 * @author gujunqi date：2013-12-27
 */
public class BphsLoginActivity extends JQActivity implements
		View.OnClickListener {
	// private final String tag = "BphsLoginActivity";
	private Button login_btn_submit;
	private EditText login_name_et, login_pwd_et;
	private String loginName, loginPwd;
	// private LinearLayout loginaccount_layout;
	// private LinearLayout loginpwd_layout;
	private RadioGroup loginRG;
	private String result;

	private SharedPreferences loginlist = null;
	private CheckBox login_saveuser;
	private Animation animation;

	String sResult;
	String sMessage;
	@Override
	protected int getContentLayout() {

		return R.layout.login_layout;
	}

	@Override
	protected void initGui() {
		login_btn_submit = (Button) findViewById(R.id.login_btn_submit);
		login_btn_submit.setOnClickListener(this);
		login_name_et = (EditText) findViewById(R.id.login_name_et);
		login_pwd_et = (EditText) findViewById(R.id.login_pwd_et);
		// loginaccount_layout = (LinearLayout)
		// findViewById(R.id.loginaccount_layout);
		// loginpwd_layout = (LinearLayout) findViewById(R.id.loginpwd_layout);
		login_saveuser = (CheckBox) findViewById(R.id.login_saveuser);
		loginRG = (RadioGroup) findViewById(R.id.loginRG);
	}

	@Override
	protected void initAction() {

		// Toast.makeText(act, DataDictionaryDao.getAllCount()+"", 1).show();
		// List<DictionaryBean> groupLists
		// =DataDictionaryDao.getGroupList("HypertensionVisiting_Symptom");
		// for(int i=0;i<groupLists.size();++i){
		// String
		// itemStr=groupLists.get(i).getItem_name()+groupLists.get(i).getItem_code();
		// Log.i(tag, "返回集合=============="+itemStr);
		// }
		// Log.i(tag, "返回集合的大小"+groupLists.size());

		// 设定设备的品牌类型
		String branch = AndroidUtil.getBranch(ctx);
		// A0000037D64A75|Android-GT1000|android 4.0.3
		// 860223024414135|Lenovo-IdeaTab S6000-H|android 4.2.2
		// Lenovo-IdeaTab S6000-H
		if ("Lenovo-IdeaTab S6000-H".equals(branch)) {
			BphsConstants.deviceBranchType = 0;
		} else if ("Android-GT1000".equals(branch)) {
			BphsConstants.deviceBranchType = 1;
		}
		//chenxu force using garea device
//		BphsConstants.deviceBranchType = 1;

	}

	private void testHeapSize(){
		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		int normalHeapSize = am.getMemoryClass();
		int largeHeapSize = am.getLargeMemoryClass();
		Log.d("chenxu", "normal:"+normalHeapSize+" large:"+largeHeapSize);
	}

	private void testByteOrder(){
		boolean isBigEndian = ByteOrderUtil.isCPUBigEndian();
		Log.d("chenxu", "isCPU BigEndian:"+isBigEndian);
	}

	@Override
	protected void initData() {
//		testByteOrder();
//		testHeapSize();

		loginlist = getSharedPreferences("LOGIN_INFOS", 0);
		String ip = loginlist.getString("ip", "");
		if (StringUtils.isBlank(ip) && (BphsConstants.isProduct)) {
			to(SettingIPActivity.class);
			BphsConstants.isProduct = false;
		} else {
			BphsConstants.HTTP_SERVER_IP = loginlist.getString("ip", "");
			BphsConstants.HTTP_SERVER_PORT = loginlist.getString("port", "");
			// BphsConstants.PROJECT_PATH=loginlist.getString("path", "");
		}
		if (loginlist.getBoolean("isSaveUserNo", true)) {
			String username = loginlist.getString("UserNos", "");
			login_name_et.setText(username);
			//login_pwd_et.setText(loginlist.getString("loginPwd", ""));
			  loginPwd = loginlist.getString("loginPwd", "");
			// login_pwd_et.setText(loginPwd);
		} else {
			login_saveuser.setChecked(false);
		}
		login_saveuser
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						loginlist
								.edit()
								.putBoolean("isSaveUserNo",
										login_saveuser.isChecked()).commit();
					}
				});
		animation = AnimationUtils.loadAnimation(this, R.anim.shake);

		if (StringUtils.isBlank(NetUtil.getNetType(act))) {
			MessageTools.showDialogOk(ctx, "当前网络不可用，请选择离线登录！");
			// Toast.makeText(this, "当前网络不可用，请选择离线登录！", 1).show();
		}
		;

		if (!loginlist.getBoolean("already_read", false)) {
			Builder builder = new Builder(BphsLoginActivity.this);
			builder.setTitle("温馨提示");
			builder.setMessage("新版本升级后对于过于简单的，存在安全隐患的密码，需要您到网页上修改密码。新密码的要求如下：\r\n1. 密码长度最少为6位，不能与用户名相同。\r\n2. 密码必须为数字加字母的组合。举例说明：123456[不符合密码规范]，abc456[符合密码规范]\r\n3. 修改密码后，需要您重新在线登录系统，已修改密码的直接跳过\r\n");
			builder.setPositiveButton("已阅读", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					loginlist.edit().putBoolean("already_read", true).commit();
				}
			});
			builder.setNegativeButton("取消", new OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {

				}
			});
			AlertDialog dialog = builder.create();
			dialog.setCancelable(false);
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
		}

		// boolean isnetwork = false;
		// new Thread() {
		// public void run() {
		// NetUtil.isConnectWIFIOr3G(act);
		// }
		// }.start();
		// if (true) {
		// updateVersion();
		// }

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn_submit:
			// DictionaryDao dao=new DictionaryDao(act);
			// boolean a=dao.add("8888888888888888888888888888", "123", 88,
			// "民族", "汉族", 77);
			// if(a){
			// Log.i(tag, "点击了登录");}else{Log.i(tag, "点击了");}
			loginName = login_name_et.getText().toString().trim();
			// login_pwd_et.setText("JQKJ2902666NLX");// 设置密码
			loginPwd = login_pwd_et.getText().toString().trim();// 密码

			if (StringUtils.isBlank(loginName)) {
				login_name_et.startAnimation(animation);
				return;
			}
			if (StringUtils.isBlank(loginPwd)) {
				login_pwd_et.startAnimation(animation);
				return;
			}
			if (loginPwd.length() < 6) {
				MessageTools.showDialogOk(ctx, "密码长度小于6位，请在网页上重新设置你的密码！");
				return;
			}
			if (StringTools.isNumOnly(loginPwd)) {
				MessageTools.showDialogOk(ctx, "密码不能为纯数字，请在网页上重新设置你的密码！");
				return;
			}
			if (StringTools.isLowerOrUpperCase(loginPwd)) {
				MessageTools.showDialogOk(ctx, "密码不能为纯字母，请在网页上重新设置你的密码！");
				return;
			}
			if (loginPwd.equals(loginName)) {
				MessageTools.showDialogOk(ctx, "密码不能和用户名相同，请在网页上重新设置你的密码！");
				return;
			}
			boolean netischeck = false;
			int id = loginRG.getCheckedRadioButtonId();
			switch (id) {
			case R.id.lianwangRB:
				BphsConstants.isNetAvailable = true;
				netischeck = true;
				break;
			case R.id.lixianRB:
				BphsConstants.isNetAvailable = false;
				netischeck = true;
				break;
			default:
				netischeck = false;
				Toast.makeText(this, "请选择一种方式登录！", Toast.LENGTH_SHORT).show();
				break;
			}
			if (netischeck) {
				loadWaitPanel();
				LoginMethod();
			}

			// to(MainFunctionActivity.class);

			// Toast.makeText(act, result, 0).show();
			return;
		}

	}

	public void LoginMethod() {
		if (!BphsConstants.isNetAvailable) {
			String pwd = loginlist.getString("loginPwd", "");
			if (pwd.equals(loginPwd)) {
				result = loginlist.getString("result", "");
				parseResultJson(result);
			} else {
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "用户名密码不一致，请重新登录！");
				// Toast.makeText(this, "用户名密码不一致，请重新登录！", 1).show();
			}
		} else {
			final JSONObject logindata = new JSONObject();
			try {
				logindata.put("sLoginName", loginName);
				logindata.put("sPassword", loginPwd);
				// {"sLoginName":"admin","sPassword":"123"}
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			new Thread() {
				public void run() {
					String serviceURL = BphsURL.getCommonPath("LOGIN_URL");
					// String methodName= BphsURL.getCommonPath("LOGIN_METHOD");
					String methodName = "GetUserInfo";
					// String serviceURL =
					// "http://60.171.146.122:9098/WebService/AndrewsWebService.asmx";
					// String serviceURL =
					// "http://192.168.44.163:9099/WebService/AndrewsWebService.asmx";
					result = WebServiceUtils.requestByParams(methodName,
							logindata.toString(), serviceURL);
					// {"sSuccess":"1","sMessage":"用户登陆成功！","AllCount":0,"Data":"{\"sResult\":null,\"sMessage\":null,\"sLoginName\":\"admin\",\"sAlias\":null,\"sUserName\":\"安徽省卫生厅\",\"sOrganizationKey\":\"60bfbec0-180e-41b9-9974-007ef0d0ee43\",\"sOrgInstitutionCode\":\"X19870226\",\"sOrganizationName\":\"安徽省卫生厅\",\"sOrganizationTypeCode\":\"10\",\"sOrganizationLevelCode\":\"1\",\"sManagementDivisionCode\":\"340000\",\"sManagementDivisionName\":\"安徽省\"}"}
					// {"sSuccess":"1","sMessage":"用户登陆成功！","AllCount":0,"Data":"[{\"sResult\":null,\"sMessage\":null,\"sLoginName\":\"admin\",\"sAlias\":\"admin\",\"sUserName\":\"阜阳市卫生局\",\"sOrganizationKey\":\"341200101124000001\",\"sOrgInstitutionCode\":null,\"sOrganizationName\":\"阜阳市卫生局\",\"sOrganizationTypeCode\":null,\"sOrganizationLevelCode\":\"2\",\"sManagementDivisionCode\":\"341200\",\"sManagementDivisionName\":\"阜阳市\",\"sAndroidReader\":\"1\"},{\"sDoctorList\":[{\"sPersonName\":\"李三\",\"sSexName\":\"\",\"sPhone\":\"\",\"sEmail\":\"\",\"sAddress\":\"\",\"gKey\":\"859f80be-3eb8-484f-8961-320ef3bd1a7f\",\"sOrganizationName\":\"阜阳市卫生局\",\"sSexCode\":\"\",\"iState\":\"1\",\"Personkey\":\"93fba4cc-3c81-46f6-9b32-e0410f6ea3bf\"},{\"sPersonName\":\"张四\",\"sSexName\":\"\",\"sPhone\":\"\",\"sEmail\":\"\",\"sAddress\":\"\",\"gKey\":\"84505a28-276a-4c96-94e8-ffa51dba4337\",\"sOrganizationName\":\"阜阳市卫生局\",\"sSexCode\":\"\",\"iState\":\"1\",\"Personkey\":\"93fba4cc-3c81-46f6-9b32-e0410f6ea3bf\"},{\"sPersonName\":\"王六\",\"sSexName\":\"\",\"sPhone\":\"\",\"sEmail\":\"\",\"sAddress\":\"\",\"gKey\":\"b4c9e9ee-40a5-4e56-b866-2505b1ede226\",\"sOrganizationName\":\"阜阳市卫生局\",\"sSexCode\":\"\",\"iState\":\"1\",\"Personkey\":\"93fba4cc-3c81-46f6-9b32-e0410f6ea3bf\"},{\"sPersonName\":\"杨二\",\"sSexName\":\"\",\"sPhone\":\"\",\"sEmail\":\"\",\"sAddress\":\"\",\"gKey\":\"a22cd3dc-f15f-4158-8954-aecdc815534f\",\"sOrganizationName\":\"阜阳市卫生局\",\"sSexCode\":\"\",\"iState\":\"1\",\"Personkey\":\"93fba4cc-3c81-46f6-9b32-e0410f6ea3bf\"},{\"sPersonName\":\"宋一\",\"sSexName\":\"\",\"sPhone\":\"\",\"sEmail\":\"\",\"sAddress\":\"\",\"gKey\":\"add53d78-ddc0-4e21-a552-c28327d0201e\",\"sOrganizationName\":\"阜阳市卫生局\",\"sSexCode\":\"\",\"iState\":\"1\",\"Personkey\":\"93fba4cc-3c81-46f6-9b32-e0410f6ea3bf\"}]}]"}
					parseResultJson(result);
				}
			}.start();
		}
	}

	// 下载更新相关
	String curAppUrl = "";
	private final int SPLASH_TIME = 0;
	private final Handler showDownLoadHandle = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SPLASH_TIME:
				Uri uri = Uri.parse(curAppUrl);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				((Activity) act).startActivityForResult(intent, 0);
				exitSystem();
				break;
			case Constant.MSG_LOAD_OVER:
				dismissrogressBar();
				if ("1".equals(sResult)) {
					if (login_saveuser.isChecked()) {
						loginlist.edit().putBoolean("already_read", true)
								.commit();

						loginlist.edit().putString("UserNos", loginName)
								.commit();
 						loginlist.edit().putString("loginPwd", loginPwd)
 								.commit();
						loginlist.edit().putString("result", result).commit();
					}
//					jumpToMainFunctionActivityWithoutFinishSelf();
					to(MainFunctionActivity.class);
				} else {
					MessageTools.showDialogOk(ctx, sMessage);
				}
				break;
			case Constant.MSG_LOAD_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "登录请求失败！");
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void jumpToMainFunctionActivityWithoutFinishSelf(){
		toNoFinish(MainFunctionActivity.class);
	}

	private void updateVersion() {
		// 1表示有效；2表示有更新版本；3表示强制更新
		UserLoginInfo loginInfo = UserLoginInfo.getInstances();
		String status = loginInfo.getUpdateStatus();
		String msg = loginInfo.getUpdateMessage();
		this.curAppUrl = loginInfo.getUpdateUrl();
		Builder builder = new Builder(act);
		builder.setCancelable(false);
		if (Constant.UPDATE_STATUS_RECOMMEND.equals(status)) {
			if (CommonUtil.isStringEmpty(msg)) {
				msg = "为更好地为您提供服务，您的公共卫生服务应用有更新，请保证您的设备有足够的空间。\n若未满足以上条件，您也可以选择卸载旧版本后重新下载。\n您要更新吗？";
			}
			// 有更新版本 提示更新
			// 强制更新
			// 有更新版本 提示更新
			builder.setMessage(msg);
			builder.setPositiveButton(Constant.UPDATE_NOW,
					new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							final Message msg = new Message();
							msg.what = 0;
							showDownLoadHandle.sendMessageDelayed(msg,
									SPLASH_TIME);
						}
					});
			builder.setNegativeButton(Constant.UPDATE_DELAY,
					new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// 客户取消更新，显示银行公告
						}
					});
			MessageTools.showDialog(builder);
			loginInfo.setShowedUpdateMessage(true);
		} else if (Constant.UPDATE_STATUS_FORCE.equals(status)) {
			if (CommonUtil.isStringEmpty(msg)) {
				msg = "为更好地为您提供服务，您的公共卫生服务应用需更新，请保证您的设备有足够的空间。\n若未满足以上条件，您也可以选择卸载旧版本后重新下载。";
			}
			// 强制更新
			builder.setMessage(msg);
			builder.setPositiveButton(Constant.UPDATE_NOW,
					new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							final Message msg = new Message();
							msg.what = 0;
							showDownLoadHandle.sendMessageDelayed(msg,
									SPLASH_TIME);
						}
					});
			MessageTools.showDialog(builder);
			loginInfo.setShowedUpdateMessage(true);
		}
	}

	private void parseResultJson(String result) {
		if (StringUtils.isNotBlank(result)) {

			JSONObject json;
			UserLoginInfo info = UserLoginInfo.getInstances();
			try {
				json = new JSONObject(result);
				sResult = json.getString("sSuccess");
				sMessage = json.getString("sMessage");
				String a = json.getString("Data");
				JSONArray jsonArray1 = new JSONArray(a);
				if ("0".equals(sResult)) {
					showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				} else {

					for (int i = 0; i < jsonArray1.length(); ++i) {

						if (i == 0) {
							JSONObject jsonData = (JSONObject) jsonArray1
									.get(i);
							info.setsLoginName(jsonData.getString("sLoginName"));
							info.setsAlias(jsonData.getString("sAlias"));
							info.setsUserName(jsonData.getString("sUserName"));
							info.setsOrganizationKey(jsonData
									.getString("sOrganizationKey"));
							info.setsOrgInstitutionCode(jsonData
									.getString("sOrgInstitutionCode"));
							info.setsOrganizationName(jsonData
									.getString("sOrganizationName"));
							info.setsOrganizationTypeCode(jsonData
									.getString("sOrganizationTypeCode"));
							info.setsOrganizationLevelCode(jsonData
									.getString("sOrganizationLevelCode"));
							info.setsManagementDivisionCode(jsonData
									.getString("sManagementDivisionCode"));
							info.setsManagementDivisionName(jsonData
									.getString("sManagementDivisionName"));
							info.setsAndroidReader(jsonData
									.getString("sAndroidReader"));
							BphsConstants.sAndroidReader = ("1".equals(jsonData
									.getString("sAndroidReader")));
							// BphsConstants.sAndroidReader=false;
						}
						if (i == 1) {
							if (TextUtils.isEmpty(jsonArray1.get(i).toString())) {

							} else {
								JSONObject jsonData = (JSONObject) jsonArray1
										.get(i);
								JSONArray jsDoctorList = (JSONArray) jsonData
										.get("sDoctorList");
								// for (int j = 0; j < jsDoctorList.length();
								// ++j) {
								// JSONObject jsonDoctor = (JSONObject)
								// jsDoctorList.get(j);
								// sDoctorNameList.add(jsonDoctor.getString("sPersonName"));
								// }
								// info.setsDoctorNameList(sDoctorNameList);
								info.setJsonArrayDoctors(jsDoctorList);
							}

						}

					}
					showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
		}
	};
}
